import React from "react";
import { useRequest } from "ahooks";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  ColumnDef,
  ColumnFiltersState,
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  SortingState,
  useReactTable,
  VisibilityState,
} from "@tanstack/react-table";
import {
  ArrowUpDown,
  ChevronLeftIcon,
  ChevronRightIcon,
  ChevronsLeft,
  ChevronsRight,
  Edit,
  MoreHorizontal,
  Trash,
  Plus,
} from "lucide-react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import { AccessLogStatsI, ResourceI, RoleI, TenantI } from "@/types";
import PageContainer from "@/components/layout/page-container";
import CustomTable from "@/components/ui/custom-table";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { searchAccessLogList } from "@/api";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Loading } from "@/components/ui/loading";
import { dayjs } from "@/App";
import { CustomDatePicker } from "@/components/ui/datepicker";

const page: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  const { toast } = useToast();

  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [accessLogList, setAccessLogList] = React.useState<RoleI[]>([]);

  const formSchema = z.object({
    startDate: z.date(),
    endDate: z.date(),
  });

  const defaultValues = {
    startDate: dayjs("2023-01-01").toDate(),
    endDate: dayjs().toDate(),
  };

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  // 2. Define a submit handler.
  function onSubmit(values: z.infer<typeof formSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    console.log(values);
    const params = new URLSearchParams();
    params.set("startDate", JSON.stringify(values.startDate));
    params.set("endDate", JSON.stringify(values.endDate));

    navigate(`${location.pathname}?${params.toString()}`);
    run(params.toString());
  }

  const { loading, run } = useRequest(
    (paramsString: string) => searchAccessLogList(paramsString),
    {
      manual: true,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params: any) {
        // console.log(resp.data.data);
        setAccessLogList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(e: any, params: any) {
        // console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: "请检查网络或联系系统管理员",
        });
      },
    }
  );

  const columnHelper = createColumnHelper<AccessLogStatsI>();

  const columns = [
    columnHelper.accessor("statsDate", {
      id: "statsDate",
      header: "访问日期",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("statsDate")}</span>;
        }
      },
      enableSorting: true,
    }),
    columnHelper.accessor("username", {
      id: "username",
      header: "用户名",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("username")}</span>;
        }
      },
      enableSorting: true,
    }),
    columnHelper.accessor("fullName", {
      id: "fullName",
      header: "姓名",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("fullName")}</span>;
        }
      },
      enableSorting: true,
    }),
    columnHelper.accessor("accessCount", {
      id: "accessCount",
      header: "访问次数",
      enableSorting: true,
    }),
  ];

  React.useEffect(() => {
    // console.log(searchParams.toString());
    run(searchParams.toString());
  }, [searchParams]);

  return (
    <PageContainer>
      <div className="space-y-4">
        {/* <Breadcrumbs items={breadcrumbItems} /> */}
        <div className="w-full py-6 border p-3">
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(onSubmit)}
              className="flex items-center space-x-4"
            >
              <FormField
                control={form.control}
                name="startDate"
                render={({ field }) => (
                  <FormItem>
                    {/* <FormLabel>开始时间</FormLabel> */}
                    <FormControl>
                      <CustomDatePicker
                        placeholder="开始时间"
                        value={field.value}
                        onChange={field.onChange}
                        startMonth={dayjs().subtract(2, "year").toDate()}
                        endMonth={dayjs().add(1, "year").toDate()}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="endDate"
                render={({ field }) => (
                  <FormItem>
                    {/* <FormLabel>结束时间</FormLabel> */}
                    <FormControl>
                      <CustomDatePicker
                        placeholder="结束时间"
                        value={field.value}
                        onChange={field.onChange}
                        startMonth={dayjs().subtract(2, "years").toDate()}
                        endMonth={dayjs().add(1, "years").toDate()}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <Button type="submit">查询</Button>
            </form>
          </Form>
        </div>

        <Separator />
        <CustomDndTable
          defaultFilterColumn="name"
          totalCount={totalCount}
          columns={columns}
          loading={loading}
          data={accessLogList}
        />
      </div>
    </PageContainer>
  );
};

export default page;
